package com.hong.spring.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WebsocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ChannelHandler nettyWebSocketHandler;

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        //基于http协议，使用http的编码和解码器
        pipeline.addLast(new HttpServerCodec());
        //是以块方式写，添加ChunkedWriteHandler处理器
        pipeline.addLast(new ChunkedWriteHandler());
        //http在传输过程中分段
        pipeline.addLast(new HttpObjectAggregator(8192));
        //心跳
        //pipeline.addLast(new IdleStateHandler(20L, 0L, 0L, TimeUnit.SECONDS));
        //将http升级为websocket
        pipeline.addLast(new WebSocketServerProtocolHandler("/hong"));
        //pipeline.addLast(new NettyServerHandler());
        
        pipeline.addLast(nettyWebSocketHandler);
    }
}